package com.example.result

import android.content.Context
import android.media.metrics.Event
import android.os.Environment
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.uiautomator.By
import androidx.test.uiautomator.Direction
import androidx.test.uiautomator.UiDevice
import androidx.test.uiautomator.Until
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import java.io.File

@RunWith(AndroidJUnit4::class)
class BookScreenTest {
    lateinit var device: UiDevice
    lateinit var context: Context

    @Before
    fun before() {
        val instrumentation = InstrumentationRegistry.getInstrumentation()
        context = instrumentation.targetContext
        device = UiDevice.getInstance(instrumentation)
        val packageName = context.packageName
//         context.startActivity(intent)
        val activityName = MainActivity::class.java.name
        device.launchActivity(packageName, activityName)
        enterBookScreen(device, context)
    }

    @Test
    fun testGrantFileReadAndManagerPermission() {
        val packageName = context.packageName
        device.waitAndFindObject(By.textEndsWith("/0"))!!.click()
        device.waitAndFindObject(By.text("外部文件读取权限"))!!.click()
        device.takeScreenshot()
        device.performActionAndWait({}, Until.newWindow(), LAUNCH_TIMEOUT)
        device.waitAndFindObject(By.textContains("始终允许"))!!.click()
        device.performActionAndWait({}, Until.newWindow(), LAUNCH_TIMEOUT)
        val bt = device.waitAndFindObject(By.text("授予管理所有文件的权限"))
        device.performActionAndWait({
            bt!!.click()
        }, Until.newWindow(), LAUNCH_TIMEOUT)
        val appName = context.getString(R.string.app_name)
        device.waitAndFindObject(By.text(appName), true)!!
            .clickAndWait(Until.newWindow(), LAUNCH_TIMEOUT)
        device.waitAndFindObject(By.text("授予管理所有文件的权限"))!!.click()
        device.wait(Until.hasObject(By.checked(true)), LAUNCH_TIMEOUT)
        device.pressBack()
        device.pressBack()
        device.wait(
            Until.hasObject(By.pkg(packageName).depth(0)),
            LAUNCH_TIMEOUT
        )
        device.waitAndFindObject(By.textEndsWith(".ss"), true)!!.click()
        device.waitForWindowUpdate(packageName, LAUNCH_TIMEOUT)
        device.takeScreenshot()

    }

    private fun enterBookScreen(device: UiDevice, context: Context) {
        device.findObject(By.scrollable(true)).scroll(Direction.DOWN, 0.5f)
        device.findObject(By.scrollable(true)).swipe(Direction.RIGHT, 0.5f)
        device.waitAndFindObject(By.text(context.getString(R.string.books)))!!.click()
    }

}